//
//  ST_PairsLoveItemView.swift
//  btvideo
//
//  Created by mac on 2020/1/20.
//  Copyright © 2020 JarvanZhang. All rights reserved.
//

import UIKit
import SnapKit
import SwifterSwift
import SnapKit
import AVFoundation
import MediaPlayer
import AudioToolbox
import HandyJSON
import SDWebImage
import NIMSDK
import RealmSwift
import VideoToolbox
import KTVHTTPCache
import SwiftyUserDefaults
import SwiftyJSON

class ST_PairsLoveItemView: UIView {
    
    //    MARK: - Init
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        
        self.backgroundColor = Color.white
        self.cornerRadius = 20
        //        封面图
        self.addSubview(cover_image_view)
        cover_image_view.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
        
        self.addSubview(gradient)
        gradient.snp.makeConstraints { (make) in
            make.left.right.bottom.equalToSuperview()
            make.height.equalTo(220)
        }
        
        self.addSubview(username_label)
        self.addSubview(ageLabel)
        self.addSubview(content_label)
        
        content_label.snp.makeConstraints { (make) in
            make.bottom.equalToSuperview().offset(-100)
            make.left.equalToSuperview().offset(10)
        }
        
        username_label.snp.makeConstraints { (make) in
            make.bottom.equalTo(content_label.snp.top).offset(-5)
            make.left.equalToSuperview().offset(10)
        }
        
        ageLabel.snp.makeConstraints { (make) in
            make.bottom.equalTo(username_label)
            make.left.equalTo(username_label.snp.right).offset(5)
        }
        
        
        self.addSubview(mylove_view)
        mylove_view.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(10)
            make.right.equalToSuperview().offset(-10)
            make.bottom.equalToSuperview().offset(-10)
            make.height.equalTo(80)
        }
        
        
        self.addSubview(shelove_view)
        shelove_view.snp.makeConstraints { (make) in
            make.edges.equalTo(mylove_view)
        }
        
        
        self.addSubview(video_progress_view)
        
        video_progress_view.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(18)
            make.right.equalToSuperview().offset(-18)
            make.top.equalToSuperview().offset(10)
            make.height.equalTo(ST_PlayVideoProgressView.height)
        }
        
        let nextVideoWidth = 150
         self.addSubview(next_video_btn)
         self.addSubview(previous_video_btn)
         next_video_btn.snp.makeConstraints { (make) in
             make.right.top.bottom.equalToSuperview()
             make.width.equalTo(nextVideoWidth)
         }
         
         previous_video_btn.snp.makeConstraints { (make) in
             make.left.top.bottom.equalToSuperview()
             make.width.equalTo(nextVideoWidth)
         }
        
        self.addSubview(preview_btn)
        preview_btn.snp.makeConstraints { (make) in
            make.left.equalTo(previous_video_btn.snp.right)
            make.bottom.top.equalToSuperview()
            make.right.equalTo(next_video_btn.snp.left)
        }
        
        self.addSubview(preview_copy_btn)
        preview_copy_btn.snp.makeConstraints { (make) in
            make.left.equalTo(username_label)
            make.top.equalTo(username_label).offset(-10)
            make.bottom.equalTo(content_label).offset(5)
            make.width.equalTo(120)
        }
        
        
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
//    MARK: -  player properties
    
    //    播放中
    fileprivate var playing = false

    fileprivate var player:AVPlayer?

    fileprivate var time_observer:Any?

    fileprivate var playerItem:AVPlayerItem?

//    fileprivate var playerLayer:AVPlayerLayer?
    
    fileprivate var avPlayerView:ST_PairsAVPlayerView?
    
    fileprivate var currentVideoIndex = 0
    
    //    MARK: - Properties
    fileprivate lazy var video_progress_view:ST_PlayVideoProgressView = {
        let control = ST_PlayVideoProgressView()
        return control
    }()
    
    fileprivate lazy var next_video_btn:UIButton = {
       
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        
//        control.backgroundColor = Color.init(white: 0, alpha: 0.2)
        
        control.addTarget(self, action: #selector(play_next_video), for: UIControl.Event.touchUpInside)
        
        return control
    }()

    fileprivate lazy var preview_btn:UIButton = {
               
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        
//        control.backgroundColor = Color.init(white: 0, alpha: 0.2)
        
        control.addTarget(self, action: #selector(push_center_handle), for: UIControl.Event.touchUpInside)
        
        return control
    }()
    /**
     增加点击 范围跟 preview_btn 一样
     */
    fileprivate lazy var preview_copy_btn:UIButton = {
                   
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        control.addTarget(self, action: #selector(push_center_handle), for: UIControl.Event.touchUpInside)
        
        return control
    }()
    
    
    fileprivate lazy var previous_video_btn:UIButton = {
       
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        
//        control.backgroundColor = Color.init(white: 0, alpha: 0.2)
        
        control.addTarget(self, action: #selector(play_previous_video), for: UIControl.Event.touchUpInside)
        
        return control
    }()
    
    fileprivate lazy var cover_image_view:UIImageView = {
        
        let control = UIImageView()
        control.contentMode = UIView.ContentMode.scaleAspectFill
        control.backgroundColor = Color.black
        return control
    }()
    
    fileprivate lazy var gradient:ST_FWGradientView = {
        let control = ST_FWGradientView()
        control.bgLayer.colors = [UIColor.init(hex: 0x1F1F1F, transparency: 0)!.cgColor, UIColor.init(white: 0, alpha: 0.3).cgColor]
        control.bgLayer.locations = [0, 1]
        control.bgLayer.startPoint = CGPoint(x: 0, y: 0)
        control.bgLayer.endPoint = CGPoint(x: 0, y: 1)
        return control
    }()
    
    
    fileprivate lazy var content_label:UILabel = {
        let control = UILabel.init()
        control.text = ""
        control.textColor = Color.white
        //        control.numberOfLines = 0
        //        control.textAlignment = .center
        control.font = UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.medium)
        return control
    }()
    
    fileprivate lazy var username_label:UILabel = {
        let control = UILabel.init()
        control.text = ""
        control.textColor = Color.white
        //        control.numberOfLines = 0
        //        control.textAlignment = .center
        control.font = UIFont.systemFont(ofSize: 20, weight: UIFont.Weight.semibold)
        return control
    }()
    
    fileprivate lazy var ageLabel:UILabel = {
        let control = UILabel.init()
        control.text = ""
        control.textColor = Color.white
        //        control.numberOfLines = 0
        //        control.textAlignment = .center
        control.font = UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.regular)
        return control
    }()
    
    
    fileprivate lazy var mylove_view:ST_PairsLoveItemMylikeView = {
        let control = ST_PairsLoveItemMylikeView()
        control.isHidden = true
        return control
    }()
    
    fileprivate lazy var shelove_view:ST_PairsLoveItemShelikeView = {
        let control = ST_PairsLoveItemShelikeView()
        control.isHidden = true
        return control
    }()
    
//    MARK: - animation param
    fileprivate var tips_duration:TimeInterval = 0.15
    
    fileprivate var tipsAngle = CGFloat.pi/180.0 * -10.0
    
    fileprivate var xAngle = CGFloat.pi/180.0 * 4.0
    
    fileprivate var animateIdx = 0
    
    fileprivate var tips_transform:CATransform3D!
//    MARK:- Bind Model
    fileprivate var model = ST_PairsLoveItemViewModel()
    
    var love_square_operation = true
    
    func bind_view_data_set(model:ST_PairsLoveItemViewModel)  {
        
        self.model = model
        
        
        if let item_model =  self.model.album[safe: currentVideoIndex]{
            
            cover_image_view.pin_setImage(from: item_model.imageUrl.compress_image().url, placeholderImage: ST_SwiftConst.shared.fetch_random_place_holder_image())
        }
        
        username_label.text = model.nickname
        
        ageLabel.text = model.age.string + "岁"
        
        content_label.text = model.address + "  " + model.distance
        
        if model.rule_type == 1{
            
            mylove_view.isHidden = false
            shelove_view.isHidden = true
            
            mylove_view.bind_model(model.rule_data_one, rule_count: model.rule_count)
            
        }else{
            
            mylove_view.isHidden = true
            shelove_view.isHidden = false
            
            var str = "拥有的特质"
            
            if model.rule_type == 3{
                str = "喜欢的特质"
            }
            
            if let sex = ST_BTUserInfoManager.shared.current_account_info?.userinfo?.sex,sex == .female{
                str = "他" + str
            }else{
                str = "她" + str
            }
            
            shelove_view.bind_model(strArray: model.rule_data_two, title: str)
            
        }
        
        video_progress_view.create_items(count: model.album.count)
         
        video_progress_view.isHidden = model.album.count < 2
    }
    
}

//MARK:- Play Video
extension ST_PairsLoveItemView{
    
    

    //    循环播放
    @objc func player_item_did_reach_end(notification: Notification) {
      
        if let playerItem = notification.object as? AVPlayerItem{
                        
            if let currentItem = self.player?.currentItem,playerItem == currentItem{
                
                self.player?.seek(to: CMTime.zero)
                self.player?.play()
                
                return
            }
        }
    }
    
    
        
    func play(){
        
        guard let item_model =  self.model.album[safe: currentVideoIndex] , let playUrl = item_model.videoUrl.url else {
            return
        }
        
        self.play(url: playUrl, duration: item_model.duration)
        
    }
    
    
    fileprivate func play(url:URL,duration:Int) {
     
        do {
            try AVAudioSession.sharedInstance().setCategory(AVAudioSession.Category.playback)
        }catch{
            print("AVAudioSession.Category.playback Error")
        }
        
        guard let pUrl = KTVHTTPCache.proxyURL(withOriginalURL: url) else{
           print("缓存方案 创建代理Url失败：\(url)")
           return
        }
        
        let playerItem = AVPlayerItem(url: pUrl)
        
        self.playerItem = playerItem

        //创建ACplayer：负责视频播放
        self.player = AVPlayer.init(playerItem: playerItem)
        self.player?.isMuted = true
        self.player?.rate = 1.0//播放速度 播放前设置
        //进度条
        let mainQueue = DispatchQueue.main
        
        NotificationCenter.default.addObserver(self,
        selector: #selector(player_item_did_reach_end(notification:)),
        name: .AVPlayerItemDidPlayToEndTime,
        object: player?.currentItem)
        
        // Invoke callback every second
        let interval = CMTime(seconds:1.0/20.0, preferredTimescale: CMTimeScale(NSEC_PER_SEC))
        
        self.time_observer = self.player?.addPeriodicTimeObserver(forInterval: interval, queue: mainQueue, using: {[weak self] (time) in
                    
                let seconds = CMTimeGetSeconds(time)
                
                let d = duration < 1 ? 1 : duration
                 
                let percent = seconds/d.double
                
    //            print("当前播放的时间百分比:",percent)
                guard let strongSelf = self else{
                    return
                }
            
                strongSelf.video_progress_view.setProgress(percentValue: percent.cgFloat, currentIdx: strongSelf.currentVideoIndex)
            
        })
        
        
        //创建显示视频的图层
        avPlayerView = ST_PairsAVPlayerView()
        
        self.insertSubview(avPlayerView!, aboveSubview: cover_image_view)
        
        avPlayerView?.snp.makeConstraints({ (make) in
            make.edges.equalTo(cover_image_view)
        })
        
        guard let castedLayer = avPlayerView?.layer as? AVPlayerLayer else{
            return
        }
        
        castedLayer.player = self.player
        castedLayer.videoGravity = .resizeAspectFill
        
        guard let player = self.player else { return  }
        
        player.play()
        
        playing = true
        
    }
            
    func stop(){
        
        NotificationCenter.default.removeObserver(self, name: .AVPlayerItemDidPlayToEndTime, object: nil)
        
        playing = false
        
//        guard let playerLayer = self.playerLayer else { return  }
//        playerLayer.removeFromSuperlayer()
//        self.playerLayer = nil
        
        guard let player = self.player else { return  }
        
        if let ob = self.time_observer{
            player.removeTimeObserver(ob)
        }
        
        avPlayerView?.removeFromSuperview()
        avPlayerView = nil
        
        player.pause()
        
        self.player = nil
    }
    
}

//MARK:- Event

extension ST_PairsLoveItemView:CAAnimationDelegate{
    
    
    @objc fileprivate func push_center_handle(){
        

        let vc = ST_PairsCenterViewController()
        
        vc.accid = self.model.accid
        
        vc.love_square_operation = self.love_square_operation
        
        let nav = PairsCenterInteractiveNavigationController.init(rootViewController: vc)
        
        nav.overCurrentContext = true
        
        GlobalPresent(toController: nav)
        
    }
    
    @objc fileprivate func preview_curr_handle(){
        
        let curr = currentVideoIndex
        
        var array = [ST_MWPhoto]()
        
        for model in self.model.album{
            
            guard let url = model.imageUrl.big_remote_image().url , let media = ST_MWPhoto.init(url: url) else{continue}
            
            array.append(media)
            if model.videoUrl.count < 3{
                continue
            }
            guard let videoUrl = model.videoUrl.url else { continue }
            
            media.videoURL = videoUrl
        }
        
        guard let browser = ST_MWPhotoBrowser.init(photos: array) else{
            return
        }
        browser.displayActionButton = false
        browser.setCurrentPhotoIndex(curr.uInt)
        
        let nav = UINavigationController.init(rootViewController: browser)
        
        GlobalPresent(toController: nav)
    }
    
    @objc fileprivate func play_next_video(){
        
        
        currentVideoIndex += 1
        
        if currentVideoIndex == self.model.album.count{
            
            PlayFeedBack()
            
            currentVideoIndex -= 1
            
            
            self.play_tips_animate(angle: -self.tipsAngle)
            
            
            return
        }
        
        
        self.cover_image_view.sd_setImage(with: self.model.album[safe:currentVideoIndex]?.imageUrl.compress_image().url, placeholderImage: ST_SwiftConst.shared.fetch_random_place_holder_image(), options: SDWebImageOptions.init(),completed: nil)
        
        self.video_progress_view.setProgress(percentValue: 1, currentIdx: currentVideoIndex)
        
        /*   之前判断横竖 取消 待定
         if dataModel?.video_list[safe:currentVideoIndex]?.screen_type == 1{
             cover_image_view.contentMode = UIView.ContentMode.scaleAspectFill
         }else{
             cover_image_view.contentMode = UIView.ContentMode.scaleAspectFit
         }
         */
        
        
        self.stop()
        self.play()
        
        print("播放下一个")
    }
    
    @objc fileprivate func play_previous_video(){
        
        currentVideoIndex -= 1
        if currentVideoIndex < 0{
           currentVideoIndex = 0
            
            PlayFeedBack()
            
           self.play_tips_animate(angle: self.tipsAngle)
            
            
            return
        }
        
        print("播放上一个")
        
        self.cover_image_view.sd_setImage(with: self.model.album[safe:currentVideoIndex]?.imageUrl.compress_image().url, placeholderImage: ST_SwiftConst.shared.fetch_random_place_holder_image(), options: SDWebImageOptions.init(),completed: nil)
        
        self.video_progress_view.setProgress(percentValue: 1, currentIdx: currentVideoIndex)
        
        /*
         if dataModel?.video_list[safe:currentVideoIndex]?.screen_type == 1{
            cover_image_view.contentMode = UIView.ContentMode.scaleAspectFill
        }else{
            cover_image_view.contentMode = UIView.ContentMode.scaleAspectFit
        }
         */
        
        
        self.stop()
        self.play()
    }
    
    fileprivate func play_tips_animate(angle:CGFloat){
        
        var xa = xAngle
//        if angle < 0 {
//            xa = -xAngle
//        }
        
        let xTransform = CATransform3DMakeRotation(xa, 1, 0, 0)
        
        self.tips_transform = CATransform3DRotate(xTransform, angle, 0, 1.0, 0)
        
        let cornerAnimation = CABasicAnimation(keyPath: #keyPath(CALayer.transform))
                
        cornerAnimation.toValue = tips_transform
        
        cornerAnimation.isRemovedOnCompletion = false
//
        cornerAnimation.fillMode = .forwards
        
        cornerAnimation.duration = self.tips_duration
        
        cornerAnimation.delegate = self
        
        self.layer.add(cornerAnimation, forKey: #keyPath(CALayer.transform))
        
    }
    
    func animationDidStop(_ anim: CAAnimation, finished flag: Bool) {
       
            let cornerAnimation = CABasicAnimation(keyPath: #keyPath(CALayer.transform))

            cornerAnimation.fromValue = tips_transform
            
            cornerAnimation.toValue = CATransform3DIdentity

            cornerAnimation.duration = self.tips_duration

            self.layer.add(cornerAnimation, forKey: #keyPath(CALayer.transform))
    }
}

//MARK:- Child Views

class ST_PairsLoveItemShelikeView: UIView {
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.backgroundColor = Color.white
        self.cornerRadius = 12
        self.addSubview(content_label)
        content_label.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(15)
            make.top.equalToSuperview().offset(15)
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    fileprivate lazy var content_label:UILabel = {
        let control = UILabel.init()
        return control
    }()
    
    func bind_model(strArray:[String],title:String){

        
        let attrString = NSMutableAttributedString(string: title)
        let attr: [NSAttributedString.Key : Any] = [.font: UIFont.systemFont(ofSize: 14),.foregroundColor: UIColor(red: 0.2, green: 0.2, blue: 0.2, alpha: 1)]
        attrString.addAttributes(attr, range: NSRange(location: 0, length: attrString.length))
        content_label.attributedText = attrString
        
        for item in self.subviews{
            if content_label != item{
                item.removeFromSuperview()
            }
        }
        
        
        var lastControl:UIView?
        for (idx,item) in strArray.enumerated(){
            
//            if idx == 2{
//                continue
//            }
            
            let btn = UIButton.init(type: UIButton.ButtonType.custom)
            btn.setTitleForAllStates(item)
            btn.titleLabel?.font = UIFont.systemFont(ofSize: 12, weight: UIFont.Weight.medium)
            btn.setTitleColorForAllStates(UIColor.init(hex: 0x38CEDB)!)
            btn.cornerRadius = 12
            btn.borderColor = UIColor.init(hex: 0x38CEDB)!
            btn.borderWidth = 1
            let spacing = 12.cgFloat
            btn.contentEdgeInsets = UIEdgeInsets(top: 0, left: spacing, bottom: 0, right: spacing)
            self.addSubview(btn)
            
            btn.snp.makeConstraints { (make) in
                make.height.equalTo(24)
                make.top.equalTo(content_label.snp.bottom).offset(10)
                if let last = lastControl{
                    make.left.equalTo(last.snp.right).offset(10)
                }else{
                    make.left.equalToSuperview().offset(15)
                }
            }
            lastControl = btn
        }
        
    }
    
}


class ST_PairsLoveItemMylikeView: UIView {
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.backgroundColor = Color.white
        self.cornerRadius = 12
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    fileprivate lazy var content_label:UILabel = {
        let control = UILabel.init()
        return control
    }()
    
    func bind_model(_ array:[ST_PairsLoveItemMylikeViewModel],rule_count:Int){

        self.removeSubviews()
        
        var lastControl:UIView?
        for item in array{
            
            let btn = UIButton.init(type: UIButton.ButtonType.custom)
            btn.sd_setAllImage(with: item.image)
            btn.cornerRadius = 10
            self.addSubview(btn)
            
            btn.snp.makeConstraints { (make) in
                make.width.height.equalTo(40)
                make.centerY.equalToSuperview()
                if let last = lastControl{
                    make.left.equalTo(last.snp.right).offset(5)
                }else{
                    make.left.equalToSuperview().offset(15)
                }
            }
            lastControl = btn
        }
        
        
        if let last = lastControl{
            let label = UILabel()
            
            var ta = "她"
            
//            自己是女
            if ST_BTUserInfoManager.shared.current_account_info?.userinfo?.sex == ST_SEX.female{
                ta = "他"
            }
            
            let attrString = NSMutableAttributedString(string: "\(ta)有")
            label.numberOfLines = 0
            let attr: [NSAttributedString.Key : Any] = [.font: UIFont.systemFont(ofSize: 14),.foregroundColor: UIColor(red: 0.67, green: 0.71, blue: 0.75, alpha: 1)]
            attrString.addAttributes(attr, range: NSRange(location: 0, length: attrString.length))
            
            let attrString1 = NSMutableAttributedString(string: rule_count.string)
            
            let attr1: [NSAttributedString.Key : Any] = [.font: UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.medium),.foregroundColor: UIColor(red: 1, green: 0.76, blue: 0.03, alpha: 1)]
            
            attrString1.addAttributes(attr1, range: NSRange(location: 0, length: attrString1.length))
            
            attrString.append(attrString1)
            
            
            let attrString2 = NSMutableAttributedString(string: "个你喜欢")
            
            attrString2.addAttributes(attr, range: NSRange(location: 0, length: attrString2.length))
            
            attrString.append(attrString2)
            
            label.attributedText = attrString
            self.addSubview(label)
            label.snp.makeConstraints { (make) in
                make.left.equalTo(last.snp.right).offset(5)
                make.centerY.equalTo(last)
            }
        }
    }
}




